const { validationResult, buildCheckFunction } = require("express-validator");
const { AppError } = require("./errorHandler");
const { isValidObjectId } = require("mongoose");

// 验证请求数据
const validate = (validations) => {
  return async (req, res, next) => {
    await Promise.all(validations.map((validation) => validation.run(req)));
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log(errors.array());
      return next(new AppError(errors.array(), 400));
      res.status(400).json({
        status: "error",
        message: errors.array(),
      });
    }
    next();
  };
};

//  验证通用数据  验证id 是否有效
const ValidateObjectProp = (location, fields) => {
  return buildCheckFunction(location)(fields).custom(async (value) => {
    console.log(value,"ID");
    if (!isValidObjectId(value)) {
      return Promise.reject("ID 不是一个有效的ObjectId");
    }
  });
};

module.exports = {
  validate,
  ValidateObjectProp,
};
